package com.dmall.opening.up.records.util;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;

public final class Numbers {

    public static boolean isNaturalNumber(String value) {
        return StringUtils.isNumeric(value) && !"0".equals(value);
    }

    public static boolean greaterThanZero(Integer number) {
        return number != null && number > 0;
    }

    public static boolean greaterThanZero(Long number) {
        return number != null && number > 0;
    }

    public static Integer toInt(Object object) {
        return toInt(object, 0);
    }

    public static Integer toInt(Object object, Integer defaultValue) {
        try {
            if (object instanceof Number) {
                return ((Number) object).intValue();
            }
            return Integer.valueOf(object.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Long toLong(Object object) {
        return toLong(object, 0L);
    }

    public static Long toLong(Object object, Long defaultValue) {
        try {
            if (object instanceof Number) {
                return ((Number) object).longValue();
            }
            return Long.parseLong(object.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Double toDouble(Object object) {
        return toDouble(object, 0D);
    }

    public static Double toDouble(Object object, Double defaultValue) {
        try {
            if (object instanceof Number) {
                return ((Number) object).doubleValue();
            }
            return Double.parseDouble(object.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static BigDecimal toBigDecimal(Object object, BigDecimal defaultValue) {
        try {
            return new BigDecimal(object.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }
}
